﻿using System;
using System.Collections.Generic;
using Aquarinum.Base.Infrastructure.WebSocket.Utils;
using JWT;
using JWT.Algorithms;
using JWT.Serializers;

namespace Aquarinum.Base.Infrastructure.WebSocket.Extensions
{
    /// <summary>
    ///     jwt编码解码帮助类
    /// </summary>
    public class JwtTokenHelper
    {
        private static readonly string secretKey = "aecgsecret";

        /// <summary>
        ///     生成Jwt
        /// </summary>
        /// <param name="payloaddic"></param>
        /// <returns></returns>
        public static string EncodeJwtToken(Dictionary<string, dynamic> payloaddic)
        {
            var exp = DateTime.Now.GetUtcSecondsFromBaseTime() + 20;


            if (payloaddic == null) payloaddic = new Dictionary<string, dynamic>();
            if (!payloaddic.ContainsKey("exp"))
                payloaddic.Add("exp", exp); //20s 过期
            IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
            IJsonSerializer serializer = new JsonNetSerializer();
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);

            var token = encoder.Encode(payloaddic, secretKey);

            return token;
        }

        /// <summary>
        ///     解码Token
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public static IDictionary<string, dynamic> DecodeJwtToken(string token)
        {
            IDictionary<string, dynamic> dictPayload = null;
            try
            {
                IJsonSerializer serializer = new JsonNetSerializer();
                IDateTimeProvider provider = new UtcDateTimeProvider();
                IJwtValidator validator = new JwtValidator(serializer, provider);
                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder);
                dictPayload = decoder.DecodeToObject(token, secretKey, false);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return null;
            }

            return dictPayload;
        }
    }
}